package mongox

import (
	"gitee.com/zhongguo168a/go-nodex/dbx"
	"gitee.com/zhongguo168a/gocodes/datax/mapx"
	"gitee.com/zhongguo168a/gocodes/myx/errorx"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"strconv"
)

// ==============================================================
//
//

func init() {
	dbx.InitTableFuncMap.Store("mongo", InitTable)
}

func InitTable(itable dbx.ITable) (err error) {
	table := itable.(*Table)
	req := NewRequest(table)
	for key, val := range table.Indexs {
		err = req.CreateIndexs(val)
		if err != nil {
			err = errorx.Wrap(err, "create index: "+strconv.Itoa(key))
			return
		}
	}

	return

}

type TableSubMode int

const (
	TableSubMode_None TableSubMode = iota
	// TableSubMode_Hash 水平分表必须停机维护，手动分表
	TableSubMode_Hash
	// TableSubMode_Time 按时间分表，不需要停止维护，但搜索会有限制
	TableSubMode_Time
)

type IndexSortOrder int

const (
	IndexSortOrderAscende  IndexSortOrder = 1
	IndexSortOrderDescende IndexSortOrder = 2
)

// Table 表
type Table struct {
	// 表名
	Name string
	// 数据库名
	Database string
	// 主键
	PrimaryKey string
	// 索引
	Indexs map[int]*mongo.IndexModel
	// 分表数量，2的倍数
	SubAmount int
	// 分表模式
	SubMode TableSubMode
	//
	ItemCreator func() interface{}
}

func (table *Table) GetDBKind() string {
	return "mongo"
}

func (table *Table) GetDatabase() string {
	return table.Database
}

func (table *Table) GetName() string {
	switch table.SubMode {
	case TableSubMode_Hash:
	case TableSubMode_Time:

	}
	return table.Name
}

func (table *Table) GetSubName(subkey string) string {
	switch table.SubMode {
	case TableSubMode_Hash:
	case TableSubMode_Time:

	}
	return table.Name
}

type TableIndex struct {
	//
	Fields []*TableIndexItem
	//
	Options *options.IndexOptions
}

func (ti *TableIndex) GetParams(data interface{}) (x []interface{}) {
	m := map[string]interface{}{}

	for _, field := range ti.Fields {
		m[field.Name] = nil
	}
	data.(mapx.IToMap).ToMap(m)

	for _, field := range ti.Fields {
		dataField := m[field.Name]
		x = append(x, dataField)
	}
	return
}

type TableIndexItem struct {
	//
	Name string
	//1 为升序；-1为降序
	Sequence int
}
